package com.ying.dogying.im.handler.impl;

import cn.hutool.json.JSONUtil;
import com.ying.dogying.entity.Const;
import com.ying.dogying.im.dto.lastDto.ImLastMessage;
import com.ying.dogying.im.dto.lastDto.ImLastOutMessage;
import com.ying.dogying.im.dto.initDto.ImInitMessage;
import com.ying.dogying.im.dto.initDto.ImInitMine;
import com.ying.dogying.im.dto.initDto.ImInitTo;
import com.ying.dogying.im.handler.MessageHandler;
import com.ying.dogying.im.handler.filter.ExcludeMineChannelContextFilter;
import com.ying.dogying.service.ImChatService;
import com.ying.dogying.utils.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;

import java.util.Date;

public class ChatMessageHandler implements MessageHandler {

    private static final Logger logger = LoggerFactory.getLogger(ChatMessageHandler.class);

    @Override
    public void messageHandler(String data, WsRequest wsRequest, ChannelContext channelContext) {

        ImInitMessage imInitMessage = JSONUtil.toBean(data, ImInitMessage.class);
        imInitMessage.setType("chatMessage");
        ImInitMine mine = imInitMessage.getMine();
        ImInitTo to = imInitMessage.getTo();

        // 入redis
        ImLastMessage imLastMessage = new ImLastMessage();
        imLastMessage.setContent(mine.getContent());
        imLastMessage.setAvatar(mine.getAvatar());
        imLastMessage.setMine(false); // 是否是我发送的消息
        imLastMessage.setUsername(mine.getUsername());
        imLastMessage.setFromId(Long.valueOf(mine.getId()));
        imLastMessage.setId(Const.IM_GROUP_ID);
        imLastMessage.setTimestamp(new Date());
        imLastMessage.setType(to.getType());

        // 返回给前端
        ImLastOutMessage imLastOutMessage = new ImLastOutMessage();
        imLastOutMessage.setType("chatMessage");
        imLastOutMessage.setFrom(imLastMessage);
        String result = JSONUtil.toJsonStr(imLastOutMessage);
        WsResponse wsResponse = WsResponse.fromText(result, "utf-8");
        ExcludeMineChannelContextFilter filter = new ExcludeMineChannelContextFilter();
        filter.setCurrentContext(channelContext);
        Tio.sendToGroup(channelContext.tioConfig, Const.IM_GROUP_NAME, wsResponse, filter);

        //保存群聊信息
        ImChatService imChatService = (ImChatService) SpringUtil.getBean("imChatService");
        imChatService.setGroupHistoryMessage(imLastMessage);

    }
}
